package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"goStudy/websocket/impl"
	"net/http"
	"strings"
)

var (
	upgrader=websocket.Upgrader{
		//允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	clients map[string]*impl.Connection
)

func main()  {

	clients=make( map[string]*impl.Connection)

	http.HandleFunc("/ws", ws)

	http.ListenAndServe(":7777",nil)
}

func ws(writer http.ResponseWriter, request *http.Request)  {
	var (
		conn *websocket.Conn
		err error
		data []byte
	)

	token:=request.Header.Get("Sec-WebSocket-Protocol")
	upgrader.Subprotocols=strings.Split(token,",")
	//出错中断连接
	if conn,err=upgrader.Upgrade(writer,request,nil);err!= nil {
		return
	}
	defer conn.Close()





	c:=impl.NewConnection(conn)
	clients[token]=c
	//
	//go func() {
	//	var (err error)
	//	for{
	//		if err=c.WriteMessage([]byte("heartbeat"));err!= nil {
	//			fmt.Println(err)
	//			return
	//		}
	//
	//		time.Sleep(2*time.Second)
	//	}
	//}()

	var (
		msg impl.Msg
		to *impl.Connection
		ok bool
	)
	//websocket长连接
	for {
		//Text,binary
		if data,err=c.ReadMessage();err!= nil {
			fmt.Println(err)
			return
		}
		if err=json.Unmarshal(data,&msg);err!= nil {
			fmt.Println(err)
		}
		if to,ok=clients[msg.To]; ok {
			if err=to.WriteMessage([]byte(msg.Content));err!= nil{
				fmt.Println(err)
			}
		}else{
			if err=c.WriteMessage([]byte("对方离线"));err!= nil{
				return
			}
		}


	}


}

